package co.edu.unal.satacredito.rest.activities.visa;

import co.edu.unal.satacredito.rest.domain.visa.CreditCardTransaction;
import co.edu.unal.satacredito.rest.domain.visa.ValidationStatus;
import co.edu.unal.satacredito.rest.exceptions.visa.CannotValidateTransactionException;
import co.edu.unal.satacredito.rest.repositories.visa.ValidateVisa;
import co.edu.unal.satacredito.rest.representations.RestUri;
import co.edu.unal.satacredito.rest.representations.visa.CreditCardTransactionRepresentation;
import co.edu.unal.satacredito.rest.util.Constants;
import co.edu.unal.satacredito.rest.util.ServiceLocator;

public class ValidateCreditCardTransactionActivity {
	
	/**
	 * 
	 * @param transaction
	 * @param visaUri
	 * @return
	 * @throws CannotValidateTransactionException
	 */
	public CreditCardTransactionRepresentation validate(
			CreditCardTransaction transaction, RestUri visaUri)
			throws CannotValidateTransactionException {

		// perform validation
		transaction.setValidationStatus(doValidation(transaction));
		
		System.out.println("Validando tarjeta de credito # "+transaction.getCard().getNumber()+": "+transaction.getValidationStatus());

		return CreditCardTransactionRepresentation
				.createResponseTransactionRepresentation(transaction, visaUri);
	}
	
	/**
	 * 
	 * @param creditCardTransaction
	 * @return
	 * @throws CannotValidateTransactionException
	 */
	private ValidationStatus doValidation(
			CreditCardTransaction creditCardTransaction)
			throws CannotValidateTransactionException {
		try {

			ValidateVisa validateVisa = (ValidateVisa) ServiceLocator
					.getInstance().getResource(Constants.VISA_EJB);

			if (validateVisa
					.validateCreditCardTransaction(creditCardTransaction)) {
				return ValidationStatus.VALID;
			}

			return ValidationStatus.INVALID;

		} catch (Exception e) {
			throw new CannotValidateTransactionException(e);
		}

	}
}
